package com.atguigu.spzx.manager.helper;

import com.atguigu.spzx.model.entity.system.SysMenu;

import java.util.ArrayList;
import java.util.List;

/**
 * @Author：tzl
 * @Date：2024/1/29 14:42
 * @description: 菜单构建工具
 */
public class MenuHelper {

    /**
     * 构建菜单树结构
     * @param menuList
     * @return
     */
    public static List<SysMenu> buildTree(List<SysMenu> menuList){
        ArrayList<SysMenu> treeList = new ArrayList<>();
        for (SysMenu sysMenu : menuList) {
            // 如果父节点id为0则此节点无无父节点，查询他的子节点并放入
            if (sysMenu.getParentId().longValue() == 0) {
                treeList.add(findChildren(sysMenu, menuList));
            }
        }
        return treeList;
    }

    /**
     * 递归查找子节点
     * @param sysMenu
     * @return
     */
    private static SysMenu findChildren(SysMenu sysMenu, List<SysMenu> menuList) {
        sysMenu.setChildren(new ArrayList<SysMenu>());
        for (SysMenu childrenNode : menuList) {
            // 递归添加节点
            if (childrenNode.getParentId().longValue() == sysMenu.getId().longValue()) {
                sysMenu.getChildren().add(findChildren(childrenNode,menuList));
            }
        }
        return sysMenu;
    }
}
